﻿
CREATE PROCEDURE [dbo].[fares_AdaugaProductieRealizata]
	-- Add the parameters for the stored procedure here
	@IDDocumenteDetaliuSelectate varchar(2000), 
	@DataProductie varchar(10)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF LEN(LTRIM(RTRIM(@IDDocumenteDetaliuSelectate)))=0
		return 
    DECLARE @sel varchar(5000)
    
	SET @sel = 'INSERT INTO [ProductieRealizata]([IDDocumentDetaliu],[Data],[Cantitate]) 
		(SELECT [IDDocumentDetaliu],''' + @DataProductie + ''',dd.Cantitate - 
		COALESCE((SELECT SUM(Cantitate) FROM [ProductieRealizata] pr WHERE pr.[IDDocumentDetaliu]=dd.[IDDocumentDetaliu]),0) AS [newCantit] 
		FROM [DocumenteDetaliu] dd 
		WHERE [IDDocumentDetaliu] IN (' +  LTRIM(RTRIM(@IDDocumenteDetaliuSelectate)) + '))'
	PRINT(@sel)	
	EXEC(@sel)
	DELETE FROM [ProductieRealizata] WHERE [Cantitate]=0
	
END